//
//  TaskQRViewController.m
//  HuiJu
//
//  Created by 纪翀 on 16/2/24.
//  Copyright © 2016年 恒宇博基. All rights reserved.
//

#import "TaskQRViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ResourceDetailViewController.h"
#import "GTMBase64.h"

@interface TaskQRViewController ()<AVCaptureMetadataOutputObjectsDelegate>
{
    NSTimer *_timer;
    UIImagePickerController *_picker;
    NSDictionary *_photoInfo;
    NSString *_qr;
}
//捕捉会话
@property (nonatomic, strong) AVCaptureSession *captureSession;
//展示layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
//
@property (strong, nonatomic) CALayer *scanLayer;


@end

@implementation TaskQRViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initImagePicker];
    
    // Do any additional setup after loading the view from its nib.
    _scanLayer = nil;
    _captureSession = nil;
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self startReading];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initImagePicker{
    _picker = [[UIImagePickerController alloc] init];
    
    // 设置代理
    _picker.delegate = self;
    
    // 设置是否需要做图片编辑，default NO
    _picker.allowsEditing = YES;
}

- (BOOL)startReading {
    NSError *error;
    
    //1.初始化捕捉设备（AVCaptureDevice），类型为AVMediaTypeVideo
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //2.用captureDevice创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    
    //3.创建媒体数据输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    
    //4.实例化捕捉会话
    _captureSession = [[AVCaptureSession alloc] init];
    
    //4.1.将输入流添加到会话
    [_captureSession addInput:input];
    
    //4.2.将媒体输出流添加到会话中
    [_captureSession addOutput:captureMetadataOutput];
    
    //5.创建串行队列，并加媒体输出流添加到队列当中
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //5.1.设置代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    
    //5.2.设置输出媒体数据类型为QRCode
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil]];
    
    //6.实例化预览图层
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    //7.设置预览图层填充方式
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    //8.设置图层的frame
    [_videoPreviewLayer setFrame:_cameraView.layer.bounds];
    
    //9.将图层添加到预览view的图层上
    [_cameraView.layer addSublayer:_videoPreviewLayer];
    
    
    //10.设置扫描范围
    CGFloat XScale = _boxView.frame.origin.x/_cameraView.frame.size.width;
    CGFloat YScale = _boxView.frame.origin.y/_cameraView.frame.size.height;
    captureMetadataOutput.rectOfInterest = CGRectMake(YScale,XScale,1-YScale,1-XScale);
    //    captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
    NSLog(@"X:%f, Y:%f , W:%f, H:%f", _boxView.frame.origin.x, _boxView.frame.origin.y, _boxView.frame.size.width, _boxView.frame.size.height);
    NSLog(@"X:%f, Y:%f , W:%f, H:%f", _cameraView.frame.origin.x, _cameraView.frame.origin.y, _cameraView.frame.size.width, _cameraView.frame.size.height);
    
    //10.1.扫描框
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    
    [_cameraView addSubview:_boxView];
    [_cameraView addSubview:_bottomView];
    [_cameraView addSubview:_leftView];
    [_cameraView addSubview:_rightView];
    [_cameraView addSubview:_topView];
    
    //10.2.扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
    _scanLayer.backgroundColor = [UIColor brownColor].CGColor;
    
    [_boxView.layer addSublayer:_scanLayer];
    
//    _timer = [NSTimer scheduledTimerWithTimeInterval:10000.0f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
//    
//    [_timer fire];
    
    //10.开始扫描
    [_captureSession startRunning];
    
    
    return YES;
}

-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
    [_scanLayer removeFromSuperlayer];
//    [_timer invalidate];
//    _timer  = nil;
    [_videoPreviewLayer removeFromSuperlayer];
}


#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        NSLog(@"stoping Reading");
        [self stopReading];
        AVMetadataMachineReadableCodeObject  *metadataObj = [metadataObjects objectAtIndex:0];
        NSString *qr = [metadataObj stringValue];
        [self performSelectorOnMainThread:@selector(reportScanResult:) withObject:qr waitUntilDone:NO];
    }
}

-(void)reportScanResult:(NSString *)qr{
        NSLog(@"Got Meta");
    NSString *token = [GlobalVar getVarName:@"token"];
    
    [SendRequestClass commonRequest:@"/api/resourcedetail" postDic:@{@"token":token, @"resId":qr} completionBlock:^(NSDictionary *succDic) {
        if ([[succDic objectForKey:@"code"] intValue] == SUCC_RESP){
            NSLog(@"Success resourcedetail");
            NSDictionary *storageDic = [[succDic objectForKey:@"data"] objectForKey:@"storage"];
            NSString *storageId = [storageDic objectForKey:@"id"];
            //记录下来QR，为后面上传做准备
            _qr = qr;
            if (storageId !=nil && [storageId isEqualToString:_storageId]){
                // 打开相机 准备拍照
                if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    //        _picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    [self presentViewController:_picker animated:YES completion:nil];
                }
            }else{
                [self startReading];
            }
            

        }else{
            NSLog(@"Fail MyInfo");
            [MyHint showHint:[succDic objectForKey:@"message"]];
            [self startReading];
        }
    } failureBlock:^(NSDictionary *failDic) {
        NSLog(@"Network error");
        [MyHint showHint:@"网络出现故障"];
        [self startReading];
    }];
}

- (void)moveScanLayer:(NSTimer *)timer
{
    if (_timer == nil){
        return;
    }
    
    CGRect frame = _scanLayer.frame;
    CGFloat step = _boxView.frame.size.height/25;
    frame.origin.y += step;
    if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
    NSLog(@"moved");
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (IBAction)quitBtnClick:(id)sender {
    [self stopReading];
    [self.navigationController popViewControllerAnimated:YES];
    //        [self startReading];
}


#pragma mark - ImagePicker
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    // 退出当前界面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 选择完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    //    [_addPhotoBtn setBackgroundImage:[info objectForKey:UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
    _photoInfo = info;
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSString  *imageStr = [GTMBase64 stringByEncodingData:UIImageJPEGRepresentation([_photoInfo objectForKey:UIImagePickerControllerOriginalImage], 0.1)];
    
    NSString *token = [GlobalVar getVarName:@"token"];
    NSDictionary *postDic = @{
                              @"token":token,
                              @"storageId":_storageId,
                              @"picCode":imageStr,
                              @"resId":_qr
                              };
    [SendRequestClass commonRequest:@"/api/storagetaskdone" postDic:postDic completionBlock:^(NSDictionary *succDic) {
        if ([[succDic objectForKey:@"code"] intValue] == SUCC_RESP)
        {
            NSLog(@"Success storagetaskdone");
            [MyHint showHint:@"提交成功"];
                [self.navigationController popViewControllerAnimated:NO];
                [self.navigationController popViewControllerAnimated:NO];
        }
        else{
            NSLog(@"Fail storagetaskdone");
            [MyHint showHint:[succDic objectForKey:@"message"]];
        }
        
    } failureBlock:^(NSDictionary *failDic) {
        NSLog(@"Network error");
        [MyHint showHint:@"网络出现故障"];
    }];
}

@end
